

(function(window) {
    /************************************************VanyAjax开始************************************************/
    'use strict';
    var $ = window.$,
        Vue = window.Vue,
        METHODS = ["GET", "POST"],
        toString = Object.prototype.toString,
        defaults = {
            token: ""
        },
        Loading = ELEMENT.Loading.service,
        vue_ = new Vue();

    /*拦截button点击提交*/
    /*document.body.addEventListener("click", function(e){
    	if(e.target && e.target.nodeName.toUpperCase == "DIV") {
    	}
    });*/

    function VanyForm(el) {
        if(!el) {
            throw new Error("请传入一个表单ID或者表单DOM对象");
        }
        if(Object.prototype.toString.call(el) === "[object HTMLFormElement]") {
            this.el = el;
        } else {
            el = el.split("#")[1];
            this.el = document.getElementById(el);
        }
    };

    VanyForm.prototype = {
        valid: function(result) {
            var labels = {},
                tempLabels = this.el.getElementsByTagName("label");
            for(var i = 0; i < tempLabels.length; i++) {
                if(this._isClassExits(tempLabels[i], "el-form-item__label")) {
                    var labelName = tempLabels[i].getAttribute("for");
                    if(labelName) {
                        labels[labelName] = tempLabels[i];
                    }
                }
            }
            for(var i = 0; i < result.length; i++) {
                var key = result[i].field;
                var message = result[i].message[0];
                if(labels[key]) {
                    var parent_ = labels[key].parentNode,
                        sibling = labels[key].nextSibling,
                        nodeProps = {
                            "nodeType": "div",
                            "class": "el-form-item__error",
                            "innerHTML": message
                        };
                    this._addClass(parent_, "is-error");
                    var div_ = this._createNode(nodeProps);
                    sibling.appendChild(div_);
                } else {
                    console.log("字段" + key + "需要手工验证");
                }
            }
        },
        reset: function() {
            var errorNode = this.el.getElementsByClassName("el-form-item__error"),
                errorDiv = this.el.getElementsByClassName("is-error");

            while(errorNode.length) {
                errorNode[0].parentNode.removeChild(errorNode[0]);
            }
            while(errorDiv.length) {
                this._removeClass(errorDiv[0], "is-error");
            }
        },
        _getClass: function(el) {
            return el.className.split(" ");
        },
        _addClass: function(el, _class) {
            _class = _class.split(" ");
            var oldClasses = this._getClass(el),
                newClasses = oldClasses.concat(_class).join(" ");
            el.className = newClasses;
            return this;
        },
        _removeClass: function(el, _class) {
            var oldClasses = this._getClass(el);
            _class = _class.split(" ");
            for(var i = 0; i < _class.length; i++) {
                var index_ = this._getClassIndex(el, _class[i]);
                if(index_ !== false) {
                    oldClasses.splice(index_, 1);
                }
                el.className = oldClasses.join(" ");
            }
            return this;
        },
        _getClassIndex: function(el, _class) {
            var nodeClasses = this._getClass(el);
            for(var i = 0; i < nodeClasses.length; i++) {
                if(nodeClasses[i] === _class) {
                    return i;
                }
            }
            return false;
        },
        _isClassExits: function(el, _class) {
            var isExits = this._getClassIndex(el, _class);
            return isExits !== false;
        },
        _createNode: function(nodeProps) {
            var node_ = document.createElement(nodeProps["nodeType"]);
            node_.setAttribute("class", nodeProps["class"]);
            node_.innerHTML = nodeProps["innerHTML"];
            return node_;
        }
    };

    var VanyAjax_ = function(url, params, method, loadingTarget, userJquery) {
        try {
            defaults.token = VanyAjax.token;
        } catch(e) {
            console.log("无法获取token值");
        }
        if(!url || toString.call(url) !== "[object String]") {
            throw new Error("请求地址不能为空");
        }

        url = url;

        if(METHODS.indexOf(method) < 0) {
            method = "POST";
        }

        params = extend_(defaults, params);
        var self = this,
            promise_ = "";

        if(userJquery) {
            if($ === undefined) {
                throw new Error("如果要使用Jquery的Ajax方法，请引入Jquery。");
            }
            promise_ = $.when($.ajax({
                url: url,
                type: method,
                data: params,
                beforeSend: function() {
                    if(loadingTarget) {
                        self.showLoading(loadingTarget);
                    }
                }
            }));
        } else {
            if(method === "GET") {
                promise_ = Vue.http({
                    url: url,
                    params: params,
                    method: method,
                    timeout: 5000,
                    before: function() {
                        if(loadingTarget) {
                            self.showLoading(loadingTarget);
                        }
                    }
                });
            } else {
                promise_ = Vue.http({
                    url: url,
                    emulateJSON: true,
                    body: params,
                    timeout: 5000,
                    method: method,
                    before: function() {
                        if(loadingTarget) {
                            self.showLoading(loadingTarget);
                        }
                    }
                });
            }
        }
        this.promise_ = promise_;
    };

    VanyAjax_.prototype = {
        token: "",
        baseUrl: "",
        version: "0.0.1",
        /**
         * 成员方法，自动处理了请求异常，只需实现成功方法即可
         * fn: 回调函数
         * isShowMessage: 是否显示rspMsg
         * vueInstance: vue实例
         * VanyAjaxInstance.done(function(data)){成功业务逻辑代码};
         */
        done: function(fn, isShowMessage, vueInstance) {
            var self = this,
                type = "success",
                rspMsg = "",
                rspCode = "";
            /*jQuery的Ajax*/
            if(this.promise_.done) {
                this.promise_.done(function(data) {
                    if(data.rspCode === "000000") {
                        if(vueInstance) {
                            return fn.call(vueInstance, data.resultData);
                        } else {
                            return fn.call(self, data.resultData);
                        }
                    } else {
                        // TODO 增加Jquery的promise
                        type = "error";
                    }
                    rspMsg = data.rspMsg;
                    self.showMessage(isShowMessage, type, rspMsg);
                }).fail(function(err) {
                    type = "error";
                    rspMsg = err.statusText;
                    self.showMessage(true, type, rspMsg);
                });
            }
            /*Vue的Ajax*/
            else {
                this.promise_.then(function(data) {
                    data = data.data;
                    rspMsg = data.rspMsg;
                    rspCode = data.rspCode;
                    if(rspCode === "000000") {
                        try {
                            return vueInstance.vanyform.reset();
                        } catch(e) {

                        } finally {
                            return vueInstance ? fn.call(vueInstance, data.resultData) : fn.call(self, data.resultData);
                        }
                    } else {
                        type = "error";
                        switch(rspCode) {
                            // 表单验证不通过
                            case "validationErr":
                                console.log("表单验证的情况");
                                var validateErrMsg = data.validateErrMsg;
                                var refs = vueInstance.$refs;
                                for(var form_ in refs) {
                                    if(form_.toLowerCase().indexOf("form") > -1) {
                                        refs = refs[form_].$el;
                                        break;
                                    }
                                }
                                var form_ = new VanyForm(refs);
                                form_.valid(validateErrMsg);
                                vueInstance.vanyform = form_;
                                isShowMessage = false;
                                break;
                                // 登录过期，请重新登录本系统
                            case "PERMISSIONCONSTANT_SESSIONERROR":
                                isShowMessage = true;
                                setTimeout(function() {
                                    logOut();
                                }, 1500);
                                break;
                            case "PERMISSIONCONSTANT_USER_NOPERMISSION":
                                isShowMessage = true;
                                break;
                        }
                    }
                }).catch(function(err) {
                    type = "error";
                    rspMsg = err.statusText;
                }).finally(function(data) {
                    self.showMessage(isShowMessage, type, rspMsg);
                });
            }
            return this;
        },
        error: function(fn, vueInstance) {
            // TODO 增加Jquery的promise
            var rspMsg = "";
            this.promise_.then(function(data) {
                data = data.data;
                rspMsg = data.rspMsg;
                if(data.rspCode !== "000000") {
                    vueInstance ? fn.call(vueInstance, data) : fn.call(self, data);
                }
            });
        },
        hideLoading: function() {
            var loadings = document.getElementsByClassName("is-loading");
            for(var i = 0; i < loadings.length; i++) {
                if(loadings[i].nodeName === "BUTTON") {
                    var thisClass = loadings[i].className.split(" ");
                    var loadingIndex = thisClass.indexOf("is-loading");
                    if(loadingIndex > -1) {
                        thisClass.splice(loadingIndex, 1);
                    }
                    var icons = loadings[i].getElementsByClassName("el-icon-loading");
                    for(var j = 0; j < icons.length; j++) {
                        if(icons[j].nodeName === "I") {
                            icons[j].parentNode.removeChild(icons[j]);
                        }
                    }
                    loadings[i].className = thisClass.join(" ");
                }
            }
            try {
                this.loadingInstance.close();
            } catch(e) {}
        },
        /**
         * 提示请求结果——内部方法
         * isShow: 是否显示，默认显示
         * type: 消息类型，枚举型 success|error
         * message: 消息文本
         * 无返回值
         * showMessage("error", "请求错误")
         * clearData：自定义清空弹框内容
         */
        showMessage: function(isShow, type, message) {
            this.hideLoading();
            if(isShow === false) {
                return;
            }
            if(type == "error") {
                vue_.$confirm(message, {
                    type: 'warning',
                    showCancelButton: false,
                    //cancelButtonText: "取消",
                    showConfirmButton: true,
                    confirmButtonText: '确定',
                    customClass: "notLoadingThis"
                });
                console.log(message)
            } else if(type == "success") {
                vue_.$message({
                    type: type,
                    message: message
                });
            }
        },
        showLoading: function(target) {
            this.loadingInstance = Loading({
                target: target,
                text: "拼命加载中"
            });
        }
    }

    /**
     * 将源对象合并到目标对象中去——内部方法
     * src: 源对象
     * to: 目标对象
     * return 目标对象
     * a = {"a": "a"}
     * b = {"b": "b"}
     * extend_(b, a) →
     * {a: "a", b: "b"}
     */
    function extend_(src, to) {
        if(to === undefined) {
            to = {};
        }
        for(var key in src) {
            to[key] = src[key];
        }
        return to;
    }

    function logOut() {
        var form = document.createElement("form");
        var input = document.createElement("input");
        form.setAttribute("target", "_self");
        form.setAttribute("method", "post");
        form.setAttribute("action", "/logout");
        input.setAttribute("type", "text");
        input.setAttribute("name", "token");
        input.setAttribute("value", sessionStorage.token);
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
        sessionStorage.clear();
    }

    /**
     * 封装一个Ajax对象
     * 事先应设置baseUrl和token
     * VanyAjax.baseUrl = ""
     * VanyAjax.token = ""
     * url: 请求地址
     * params: 请求参数，默认添加token
     * loadingTarget: 哪个元素要显示等待效果，可以不传
     * methods: 请求方法，默认POST
     * userJquery: 是否使用Jquery的Ajax，默认使用Vue的Ajax
     * return VanyAjax实例
     * test = VanyAjax("test.json", {userCode: "test"});
     */
    window.VanyAjax = function(url, params, methods, loadingTarget, userJquery) {
        return new VanyAjax_(url, params, methods, loadingTarget, userJquery);
    };

    window.VanyAjax.prototype = VanyAjax_.prototype;

    /************************************************VanyAjax结束************************************************/

    /************************************************VanyTable结束************************************************/
    function _createColumn(prop, label, template, zidingyi) {
        var Column = "<el-table-column prop='" + prop + "' label='" + label + "' show-overflow-tooltip ";
        if(zidingyi) {
            Column += zidingyi + ">";
        } else {
            Column += ">"
        }
        if(template) {
            Column += "<template scope='scope'>" + template + "</template></el-table-column>";
        } else {
            Column += "</el-table-column>";
        }
        return Column;
    }

    function fnToString(fn) {
        return /\*(.*?)\*/g.exec(fn.toString().replace(/\s+/g, " "))[1].trim();
    }

    function _createBtn(type, label, authority) {
        if(_hasFunction(authority)) {
            return '<el-button type = "' + (type || "primary") + '" @click = "' + authority + '" authority = "' + authority + '">' + label + '</el-button>';
        } else {
            return "";
        }
    }

    function _hasFunction(fnName) {
        var fns = sessionStorage.Jurisdiction.split(",");
        for(var i = 0; i < fns.length; i++) {
            if(fnName === fns[i]) {
                return true;
            }
        }
        return false;
    }

    function genid() {
        return Math.floor(Math.random() * (9999 - 1000 + 1) + 1000);
    }

    function _createAllBtns(btns, postion, btnNotes) {
        typeof(btnNotes) == "undefined" ? btnNotes = '': btnNotes = btnNotes;
        var results = "<div class='table-btns-oper";
        if(postion === "right") {
            results += " right'>";
            for(var i = 0; i < btns.length; i++) {
                results += _createBtn(btns[i].type, btns[i].name, btns[i].authority) + "</br></br>";
            }
        } else {
            results += "'>";
            //results = '<el-row :gutter="8"><el-col :span="12"><el-row :gutter="8"><el-col :span="12"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></el-col></el-row></el-col><el-col :span="12"><el-row type="flex" justify="end">' + results;
            for(var i = 0; i < btns.length; i++) {
                results += _createBtn(btns[i].type, btns[i].name, btns[i].authority);
            }
            //			/results += "</div></el-row></el-col></el-row>";
        }
        results += btnNotes + "</div>";
        return results;
    }

    function _createAllColumn(keys, hasSelection, hasIndex, hasPages, hasPageSizes, hasScrollPage, zidingyiTop, zidingyiBtn) {
        typeof(zidingyiTop) == "undefined" ? zidingyiTop = '': zidingyiTop = zidingyiTop;
        typeof(zidingyiBtn) == "undefined" ? zidingyiBtn = '': zidingyiBtn = zidingyiBtn;
        var tableString = zidingyiTop;
        if(hasScrollPage) {
            tableString += "<el-table class='vany-table' ref='table' :data='tableData' :height='height' highlight-current-row @row-click='rowClick' @selection-change='selectionChange'>";
        }
        if(hasPages) {
            tableString += "<el-table class='vany-table' ref='table' :data='tableData' highlight-current-row @row-click='rowClick' @selection-change='selectionChange'>";
        }
        if(hasIndex) {
            tableString += '<el-table-column type="index" width="70"></el-table-column>';
        } //序号
        if(hasSelection) {
            tableString += '<el-table-column type="selection"></el-table-column>';
        } //复选框
        for(var i = 0; i < keys.length; i++) {
            tableString += _createColumn(keys[i]["key"], keys[i]["name"], keys[i]["template"], keys[i]["zidingyi"]);
        }
        tableString += "</el-table>";
        if(hasPages) {
            if(hasPageSizes === null) {
                tableString += '<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>'
            } else {
                tableString += '<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>'
            }
        }
        return tableString + zidingyiBtn;
    }

    /**
     * 判断一个可滚动元素是否滚动到了底部
     * e: 元素
     * fn: 滚动到底部需要执行的回调
     * isScrollToBottom(div, function(){})
     */
    function isScrollToBottom(e, fn) {
        // e.srcElement存在兼容性问题，并非标准特性
        // https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
        // 支持 IE6-8
        var target_ = e.target || e.srcElement,
            // 距离顶部高度
            scrollTop = target_.scrollTop,
            // 滚动区域高度
            scrollHeight = target_.scrollHeight,
            // 文档元素高度
            clientHeight = target_.clientHeight;
        // 文档坐标和视口坐标转换，判断元素滚动到了底部
        if(scrollTop + clientHeight == scrollHeight) {
            if(fn) {
                fn.call();
            }
        }
    }

    /**
     * 函数节流器，在时间间隔内不触发函数（优化）
     * 应用场景：需要反复重复执行的事件，如快速重复点击按钮等等
     * method: 函数 function a(){}
     * throttle(a)
     */
    function throttle(method, context) {
        clearTimeout(method.tId);
        method.tId = setTimeout(function() {
            method.call(context);
        }, 100);
    }

    function VanyTable(opts) {
        var tableListData = '';
        var rowsNum = 0;
        var el_ = document.getElementById(opts.el.split("#")[1]),
            tableString = _createAllColumn(opts.keys, opts.selection, opts.index, opts.pages, opts.pageSizes, opts.scrollPage, opts.zidingyiTop, opts.zidingyiBtn),
            btnsString = _createAllBtns(opts.btns, opts.btnPostion, opts.btnNotes);
        if(opts.btnPostion === "right") {
            var row = '<el-row :gutter="20"><el-col :span="18">';
            var input_ = '<div class="elInput"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></div>';
            row = row + input_ + tableString + '</el-col><el-col :span="6">' + btnsString + '</el-col></el-row>';
            if(typeof(opts.zidingyiTop) === 'string') {
                input_ = ''
            }
            el_.innerHTML = row;
        } else if(opts.btnPostion === "bottomLeft") {
            var input_ = '<el-row :gutter="8"><el-col :span="6"><div class="elInput"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></div></el-col></el-row>';
            if(typeof(opts.zidingyiTop) === 'string') {
                input_ = ''
            }
            el_.innerHTML = input_ + tableString + btnsString;
        } else {
            var row = '<el-row :gutter="8"><el-col :span="12"><el-row :gutter="8"><el-col :span="12">';
            var input_ = '<div class="elInput"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></div>';
            if(typeof(opts.zidingyiTop) === 'string') {
                input_ = ''
            }
            el_.innerHTML = row + input_ + '</el-col></el-row></el-col><el-col :span="12"><el-row type="flex" justify="end">' + btnsString + "</div></el-row></el-col></el-row>" + tableString;
        }
        return table = new Vue({
            el: opts.el,
            data: function() {
                this.opts = opts;
                this.preParams = {};
                var self = this;
                var btns = this.opts.btns;
                for(var i = 0; i < btns.length; i++) {
                    (function(i) {
                        self[btns[i].authority] = function() {
                            btns[i].click.call(self);
                        }
                    })(i);
                }
                this._collectData = [];
                this._collectPageIndex = 1;
                this._collectNodataFlag = false;
                //              debugger
                return {
                    currentPage: 1,
                    pageSize: this.opts.pageSize || 20, //默认每页20条
                    pageSizes: this.opts.pageSizes || [10], //下拉分页
                    total: 0,
                    tableData: [],
                    sels: [],
                    params: [],
                    searchValue: "",
                    height: this.opts.height || 500,
                    nodataFlag: false, //继续加载
                    hasResetPagination: false,
                    form: {
                        Timevalue: "",
                        searchValue: "",
                        value1: "",
                        value2: "",
                        value3: "",
                        value4: "",
                        value5: "",
                        value6: "",
                        value7: "",
                        value8: "",
                    },
                    pickerOptions2: {
                        shortcuts: [{
                          text: '最近一周',
                          onClick:function(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                          }
                        }, {
                          text: '最近一个月',
                          onClick:function(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                          }
                        }, {
                          text: '最近三个月',
                          onClick:function(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                          }
                        }]
                      }
                }
            },
            mounted: function() {
                this.params = {
                    scrollPageIndex: this.currentPage, //默认第一页
                    scrollPageSize: this.pageSize, //默认每页30条
                }
                var self = this,
                    isScrollToBottom_ = function() {
                        if(self.nodataFlag || self.hasResetPagination) {
                            return false;
                        }
                        isScrollToBottom(this, self.getData);
                    };
                self.$nextTick(function() {
                    var tablebody_ = self.$refs["table"].$el.getElementsByClassName("el-table__body-wrapper")[0];
                    if(opts.scrollPage) {
                        //滚动事件
                        tablebody_.onscroll = function(e) {
                            throttle(isScrollToBottom_, e);
                        }
                    }
                });
            },
            methods: {
                handleSizeChange: function(val) {
                    this.resetPagination();
                    this.params.scrollPageSize = val;
                    this.getData();
                },
                handleCurrentChange: function(val) {
                    this.resetPagination();
                    this.params.scrollPageIndex = val;
                    this.getData();
                },
                resetPagination: function() {
                    //this.searchValue = "";
                    rowsNum = 0;
                    this.sels = [];
                    this.tableData = [];
                    this.nodataFlag = false;
                    this.params.scrollPageIndex = 1;
                },
                dateFormat: function(row, column, cellValue) {
                    //格式化标准日期
                    function format(time, format) {
                        var t = new Date(time);
                        var tf = function(i) {
                            return(i < 10 ? '0' : '') + i
                        };
                        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
                            switch(a) {
                                case 'yyyy':
                                    return tf(t.getFullYear());
                                    break;
                                case 'MM':
                                    return tf(t.getMonth() + 1);
                                    break;
                                case 'mm':
                                    return tf(t.getMinutes());
                                    break;
                                case 'dd':
                                    return tf(t.getDate());
                                    break;
                                case 'HH':
                                    return tf(t.getHours());
                                    break;
                                case 'ss':
                                    return tf(t.getSeconds());
                                    break;
                            }
                        })
                    }
                    var date = row[column.property];
                    if(date == undefined) {
                        return "";
                    }
                    date = format(date, 'yyyy-MM-dd HH:mm:ss');
                    return date;
                },
                //isNewGet,Boolean 是否为一个新的请求（true代表会重置请求参数）
                getData: function(params, isNewGet) {
                	//debugger;
                    if(isNewGet) {
                        this.resetPagination();
                    } else {
                        if(this.nodataFlag) {
                            console.log("已请求完所有数据");
                            return false;
                        }
                    }
                    if(params) {
                    	//debugger
                        params = extend_(this.params, params);
                        /**
                        if(params["Timevalue"]&&params["Timevalue"] instanceof Array&&params["Timevalue"].length==2){
                        	var sTime = dateFormat(params["Timevalue"][0].toString());
                        	var eTime = dateFormat(params["Timevalue"][1].toString());
                        	params["sTime"] = sTime;
                        	params["eTime"] = eTime;
                        	params["Timevalue"] = sTime + ";" + eTime;
                        }
                        **/
                        //var paramsObj = params;
                        //params["paramsObj"] = paramsObj;
                        // 保存这一次的请求参数
                        this.preParams = {};
                        this.preParams = extend_(params, this.preParams);
                    } else {
                        this.preParams = extend_(this.params, this.preParams);
                    }
                    if(typeof(this.opts.methodTypes) == "undefined") {
                        this.opts.methodTypes = "GET";
                    }
                    VanyAjax(this.opts.url, params || this.preParams, this.opts.methodTypes, table.$el).done(function(data) {
                        /*返回的表格数据可能有其他有用的字段*/
                        for(var key in data) {
                            if(key !== "total" || key !== "rows") {
                                this["$" + key] = data[key];
                            }
                        }
                        if(data.total === 0) {
                            this.nodataFlag = true;
                            return;
                        }
                        var totleCurrent = this.params.scrollPageSize * this.params.scrollPageIndex; //加载到当前页面时，应有的数据总数

                        if(totleCurrent >= data.total) {
                            this.nodataFlag = true;
                            //判断是否是滚动加载，滚动加载是续加，分页加载则是替换
                            if(this.opts.scrollPage) {
                                totleCurrent = data.total;
                            }
                            if(this.opts.pages) {
                                totleCurrent = data.total - this.params.scrollPageSize * (this.params.scrollPageIndex - 1); //替换当前页面时，应有的数据总数
                            }
                        }
                        var rows = data.rows;
                        var rowsLength = '';
                        if(this.opts.pages) {
                            rowsLength = this.params.scrollPageSize;
                            (rows.length < rowsLength) ? (rowsLength = rows.length) : "";
                        } else {
                            rowsLength = totleCurrent;
                        }
                        for(var i = rowsNum; i < rowsLength; i++) {
                        	if(rows[i].msgType==="1"){
                        		if( rows[i].msgContent.length>20){
                        			rows[i].msgtitle = rows[i].msgContent.substring(1, 20)+"...";
                        		}else{
                        			rows[i].msgtitle = rows[i].msgContent;
                        		}
                        	}
                            this.tableData.push(rows[i]);
                        }
                        rowsNum = totleCurrent;
                        this.params.scrollPageIndex++;
                        if(this.searchValue === "") {
                            this._collectData = this._collectData.concat(rows);
                            this._collectPageIndex = this.params.scrollPageIndex;
                            this._collectNodataFlag = this.nodataFlag;
                        }
                        this.hasResetPagination = false;
                        this.total = data.total;
                    }, false, this);
                },
                rowClick: function(row, event, column) {
                    if(this._rowClick) {
                        this._rowClick.call(this, this.tableData.indexOf(row), row, event, column);
                    }
                },
                handleEdit: function(index, row) {
                    if(this._handleEdit) {
                        this._handleEdit.call(this, index, row);
                    }
                },
                handleDel: function(index, row) {
                    if(this._handleDel) {
                        this._handleDel.call(this, index, row);
                    }
                },
                selectionChange: function(selection) {
                    if(this._selectionChange) {
                        this._selectionChange.call(this.tableData.indexOf(row), selection);
                    }
                },
                search: function() {
                	//debugger;
                    if(this._search) {
                        this.hasResetPagination = true;
                        this._search.call(this, this.searchValue);
                    }
                },
                exportExl: function() {
                	//debugger;
                    if(this._exportExl) {
                        this.hasResetPagination = true;
                        this._exportExl.call(this, this.searchValue);
                    }
                },
                _restore: function(val) {
                    if(val === "") {
                        this.tableData = [].concat(this._collectData);
                        this.params.scrollPageIndex = this._collectPageIndex;
                        this.nodataFlag = this._collectNodataFlag;
                        this.preParams.searchValue = "";
                    }
                },
                on: function(type, fn) {
                    switch(type) {
                        case "rowClick":
                            this._rowClick = fn;
                            break;
                        case "selectionChange":
                            this._selectionChange = fn;
                            break;
                        case "handleEdit":
                            this._handleEdit = fn;
                            break;
                        case "handleDel":
                            this._handleDel = fn;
                            break;
                        case "exportExl":
                            this._exportExl = fn;
                            break;
                        case "search":
                            this._search = fn;
                    }
                },
                setHeigth: function(val) {
                    this.height = val;
                }
            }
        });
    }
    window.VanyTable = VanyTable;
    /************************************************VanyTable结束************************************************/

    /************************************************VanyTree开始************************************************/
    var Treetpl = function() {
        /*<div class="elInput"><el-input placeholder="输入关键字进行过滤" v-model="filterText" icon="search">
        </el-input></div>
        <h1 class="treetitle" v-once>
        	<span v-html="icon"></span>
        	<span>{{title}}</span>
        	<span @click="rightIconClick" v-html="rightIcon" style="position: absolute; right: 20px; cursor: pointer;"></span>
        </h1>
        <el-tree :default-expanded-keys="defaultExpandedKeys" :render-content="renderContent" class="filter-tree" :data="data" :node-key="defaultProps.id" :props="defaultProps" highlight-current :expand-on-click-node="false" @node-click="handleNodeClick" :filter-node-method="filterNode" ref="tree">
        </el-tree>
        <el-dropdown :hide-on-click="false" @command="handleCommand" style="display:none" ref="contexts" trigger="click" v-if="contexts" @visible-change="showContexts">
        	<span class="el-dropdown-link">
        		<i class="el-icon-caret-bottom"></i>
        	</span>
        	<el-dropdown-menu class="vanytree-contexts" slot="dropdown">
        		<el-dropdown-item v-for="(context, index) in contexts" :key="context.name" :command="''+index" divided :disabled="context.disabled" :authority="context.authority">{{context.name}}</el-dropdown-item>
        	</el-dropdown-menu>
        </el-dropdown>
        */
    };

    function cleanContexts(contextsArray) {
        var results = [];
        if(!contextsArray) {
            return results;
        }
        for(var i = 0; i < contextsArray.length; i++) {
            if(_hasFunction(contextsArray[i].authority)) {
                contextsArray[i].disabled = false;
                results.push(contextsArray[i]);
            }
        }
        return results;
    }

    function dateFormat(d) {
        var date = new Date(d);
        return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    }
    
    function VanyTree_(setting) {
        var el = document.getElementById(setting.el);
        if(!el) {
            throw new Error("未找到该元素" + setting.el);
        }
        el.innerHTML = fnToString(Treetpl);
        el.className = "vanytree";
        if(setting.neeMove) {
            el.innerHTML = '<div style="position:relative;">'+ fnToString(Treetpl)+'<div class="moveline"></div></div>';
            el.className = "vanytree i1";
        }
        setting.contexts = cleanContexts(setting.contexts);
        var vanytree = new Vue({
            el: "#" + setting.el,
            data: function() {
                return {
                    filterText: "",
                    title: setting.title,
                    icon: setting.icon,
                    rightIcon: setting.rightIcon,
                    contexts: setting.contexts,
                    justLeft: setting.neeMove,
                    defaultExpandedKeys: [],
                    data: [],
                    defaultProps: {
                        children: setting.defaultProps.children,
                        label: setting.defaultProps.label,
                        id: setting.defaultProps.id
                    }
                };
            },
            methods: {
                getData: function(params) {
                    VanyAjax(setting.url, params, setting.type, this.$el).done(function(data) {
                        this.defaultExpandedKeys = data.map(function(item) {
                            return item.id;
                        });
                        this.data = data;
                    }, false, this);
                },
                isEmptyTree: function() {
                    return this.data.length === 0;
                },
                filterNode: function(value, data) {
                    if(!value) return true;
                    //return data.label.indexOf(value) !== -1;
                    return data[this.defaultProps.label].indexOf(value) !== -1;
                },
                handleNodeClick: function(data, node, nodeComponent) {
                    if(setting.nodeClick) {
                        setting.nodeClick.call(this, data, node, nodeComponent);
                    }
                },
                // TODO
                resizeTree: function() {

                },
                handleCommand: function(command) {
                    var i = parseInt(command);
                    setting.contexts[i].click.call(this, this.store_, this.data_);
                },
                rightIconClick: function() {
                    setting.rightIconClick.call(this, this.data);
                },
                hasPre: function(nodeObj, nodeData) {
                    var hisParent = nodeObj.parent.data;
                    var hisChildren = hisParent.children ? hisParent.children : hisParent;
                    return hisChildren.length === 1 ? false : hisChildren.indexOf(nodeData) !== 0;
                },
                hasNext: function(nodeObj, nodeData) {
                    var hisParent = nodeObj.parent.data;
                    var hisChildren = hisParent.children ? hisParent.children : hisParent;
                    return hisChildren.length === 1 ? false : hisChildren.indexOf(nodeData) !== (hisChildren.length - 1);
                },
                showContexts: function(isShow) {
                    if(isShow) {
                        var self = this;
                        setTimeout(function() {
                            self.$refs["contexts"].popperElm.style.left = self.contextsx - 100 + "px";
                            self.$refs["contexts"].popperElm.style.top = self.contextsy + "px";
                            setting.onContextShow.call(self, self.contexts, self.node_, self.data_);
                        }, 150);
                    }
                },
                /**
                renderContent: function(h, {
                    node,
                    data,
                    store
                }) {
                    var self = this;
                    if(setting.contexts && setting.contexts.length !== 0) {
                        return h("span", null, [h('span', null, node.label), h("span", {
                            "class": "context_icon",
                            style: {
                                "position": "absolute",
                                "right": "-1000px",
                                "padding": "0 10px"
                            },
                            domProps: {
                                innerHTML: '<i class="el-icon-caret-bottom"></i>',
                            },
                            on: {
                                click: function(event) {
                                    if(event.target.className === "context_icon" || event.target.parentNode.className === "context_icon") {
                                        //setting.onContextShow.call(self, data);
                                        var contexts = self.$refs["contexts"];
                                        contexts.visible = false;
                                        self.node_ = node;
                                        //self.store_ = store;
                                        self.data_ = data;
                                        self.contextsx = event.clientX + 10;
                                        self.contextsy = event.clientY;
                                        contexts.show();
                                        return;
                                    }
                                }
                            }
                        }, "")]);
                    } else {
                        return h("span", null, [h("span", null, node.label)]);
                    }
                }
                **/
            },
            mounted: function() {
                /*this.$el.onmouseover = function(e) {
                	console.log(e);
                }*/
            },
            watch: {
                filterText: function(val) {
                    this.$refs.tree.filter(val);
                }
            },
        });

        return vanytree;
    }
    window.VanyTree = function(setting) {
        return new VanyTree_(setting);
    }
    /************************************************VanyTree结束************************************************/

    /************************************************VanyFilter开始************************************************/
    var tpl = function() {
        /*<el-dialog v-model="visible" :close-on-click-modal="false" :title="title" :custom-class="customClass" size="large">
        	<el-row :gutter="20">
        		<el-col :span="16">
        			<el-tabs @tab-click="_changeTab">
        				<el-tab-pane v-for="(tab, index) in tabs" :label="tab.name" :key="tab.id">
        					<div class="container_" :class="{filter_options: tab.isPersonSeleted}">
        						<div class="filter_option" v-if="tab.isPersonSeleted">
        							<el-form :ref="tab.id + '_form'" class="option_container" :model="tab.form" :style="{height: tab.treeHeight + 'px'}">
        								<el-form-item class="option_item" v-for="option in tab.form.options" :key="option.formname">
        									<el-select
        										v-if="option.type==='select'"
        										v-model="option.model"
        										:name="option.formname"
        										filterable
        										:clearable="true"
        										:multiple="option.multiple"
        										:placeholder="'按' + option.label + '进行筛选'">
        										<el-option
        											v-for="item in option.options"
        											:key="item.value"
        											:label="item.text"
        											:value="item.value">
        										</el-option>
        									</el-select>
        									<el-input v-else :placeholder="'按' + option.label + '进行搜索'" icon="search" v-model="option.model" @keyup.enter.native="getFilterValue(index)"></el-input>
        								</el-form-item>
        							</el-form>
        							<div class="filter_btns">
        								<el-button class="reset-btn" @click="resetFilter(index)">重置</el-button>
        								<el-button class="filter-btn" type="primary" @click="getFilterValue(index)">筛选</el-button>
        							</div>
        						</div>
        						<div class="tree">
        							<el-input v-if="tab.search" placeholder="输入关键字进行过滤" :value="tab.filterText"></el-input>
        							<el-table @select="select" :height="tab.treeHeight+42" v-if="tab.isPersonSeleted" @selection-change="selectionChange($event, tab)" :ref="tab.id" :data="tab.data">
        								<el-table-column type="selection"></el-table-column>
        								<el-table-column :prop="tab.defaultProps.label" label="全选 "></el-table-column>
        								<el-table-column prop="userAccount" show-overflow-tooltip label=""></el-table-column>
        								<el-table-column prop="dept" show-overflow-tooltip label=""></el-table-column>
        							</el-table>
        							<div v-else>
        								<el-tree
        									:filter-node-method="filterNode"
        									:ref="tab.id"
        									:data="tab.data"
        									highlight-current
        									default-expand-all
        									:show-checkbox="!tab.singleSelet"
        									:node-key="tab.defaultProps.id"
        									:check-strictly="true"
        									:expand-on-click-node="false"
        									:props="tab.defaultProps"
        									@check-change="handleCheckChange"
        									@current-change="_handleCurrentChange">
        								</el-tree>
        								<div class="checkall" v-if="!tab.singleSelet">
        									<el-checkbox @change="checkAll(tab.checked, tab.id)" v-model="tab.checked">全选</el-checkbox>
        								</div>
        							</div>
        						</div>
        					</div>
        				</el-tab-pane>
        			</el-tabs>
        		</el-col>
        		<el-col :span="8">
        			<div v-for="(tab, index) in tabs" :style="tab.display" class="seleted_container">
        				<div class="title">
        					<div class="center">
        						已选{{tab.name}}{{seletedCount[index]}}
        					</div>
        					<div class="right" style="opacity: 0;">
        						保存为我的分类
        					</div>
        				</div>
        				<div class="content" :style="tab.styleObj">
        					<div class="seleted_persons">
        						<div class="seleted_person" v-for="(checked, index_) in tab.allCheckeds">
        							<img v-if="tab.icon" :src="tab.icon" width="60" height="60">
        							<img v-else :src="checked.photoUrl || '/templates/img/default.jpg'" width="60" height="60" @error="imgError($event)">
        							<p v-text="checked.name"></p>
        							<p v-if="tab.isPersonSeleted" class="remove_from_seleted" @click="remove(checked.userId, index_, tab.id , true)"><span>╳</span></p>
        							<p v-else class="remove_from_seleted" @click="remove(checked.id, index_, tab.id , true)"><span>╳</span></p>
        						</div>
        					</div>
        				</div>
        			</div>
        		</el-col>
        	</el-row>
        	<span slot="footer" class="dialog-footer">
        		<el-button type="primary" @click="submit">确 定</el-button>
        		<el-button @click="visible = false">取 消</el-button>
        	</span>
        </el-dialog>*/
    };

    function isFunction(o) {
        return Object.prototype.toString.call(o) === "[object Function]";
    }

    function VanyFilter_(setting) {
        var mountEl = setting.mountEl.split("#"),
            id = "VanyFilter" + genid(),
            div = document.createElement("div");
        div.setAttribute("id", id);
        div.innerHTML = fnToString(tpl);
        mountEl = mountEl.length === 1 ? document.getElementsByTagName(mountEl)[0] : document.getElementById(mountEl[1]);
        mountEl.appendChild(div);
        var vanyfilter = new Vue({
            el: "#" + id,
            data: function() {
                var watch = {};
                for(var i = 0; i < setting.tabs.length; i++) {
                    // 保存树数据
                    setting.tabs[i].data = [];
                    // 树高度
                    if(window.innerHeight <= 768) {
                        setting.tabs[i].treeHeight = 304;
                    } else {
                        setting.tabs[i].treeHeight = 504;
                    }

                    // TODO用于搜索
                    setting.tabs[i].filterText = "";
                    // 对于人员筛选器的过滤选项集合
                    setting.tabs[i].form = {
                        options: []
                    };
                    // 分页
                    if(setting.tabs[i].pagination) {
                        if(setting.tabs[i].params === undefined) {
                            setting.tabs[i].params = {};
                        }
                        setting.tabs[i].params.pageSize = 100;
                        setting.tabs[i].params.pageIndex = 1;
                        setting.tabs[i].nodataFlag = false;
                        setting.tabs[i].total = 0;
                        setting.tabs[i].pages = 0;
                        setting.tabs[i].pageNum = 0;
                    }
                    // 树的所有已勾选节点ID
                    setting.tabs[i].allNodesId = [];
                    // 树的所有已勾选节点
                    setting.tabs[i].allCheckeds = [];
                    // 全选状态
                    setting.tabs[i].checked = false;
                    // 单选
                    setting.tabs[i].singleSelet = setting.tabs[i].singleSelet;
                    setting.tabs[i].defaultProps = setting.tabs[i].defaultProps || {
                        children: 'children',
                        label: 'name',
                        id: "id"
                    };
                    setting.tabs[i].display = {
                        display: "none"
                    };
                    setting.tabs[i].styleObj = {
                        "height": "",
                        "overflow-y": "auto"
                    };
                    if(i === 0) {
                        setting.tabs[i].display = {
                            display: "block"
                        }
                    }
                }
                return {
                    visible: true,
                    title: setting.title,
                    tabs: setting.tabs,
                    isIE: !!window.VBArray
                }
            },
            mounted: function() {
                for(var i = 0; i < this.tabs.length; i++) {
                    !this.tabs[i].isPersonSeleted ? this.getData(this.tabs[i]) : this.getFilter(this.tabs[i]);
                }
            },
            computed: {
                seletedCount: function() {
                    return this.tabs.map(function(item) {
                        return item.allNodesId.length !== 0 ? "(" + item.allNodesId.length + ")" : "";
                    });
                },
                customClass: function() {
                    if(this.isIE) {
                        return "border_dialog center_dialog vanymodal_vueversion isIE";
                    } else {
                        return "border_dialog center_dialog vanymodal_vueversion";
                    }
                }
            },
            watch: {
                filterText: function(val) {
                    console.log(val)
                }
            },
            methods: {
                imgError: function(e) {
                    e.srcElement.src = "/templates/img/default.jpg";
                },
                /**
                 * 设置树高度
                 * tabObj：Object tab设置对象
                 */
                setHeight: function(tabObj) {
                    var ref_ = this.$refs[tabObj.id][0];
                    // 22是全选高度
                    var height_ = tabObj.treeHeight + 22;
                    if(tabObj.singleSelet) {
                        // 20是全选上下padding值
                        ref_.$el.style.height = height_ + 20 + 'px';
                        tabObj.styleObj.height = height_ + "px";
                    } else {
                        ref_.$el.style.height = tabObj.treeHeight + 'px';
                        tabObj.styleObj.height = height_ + 20 + "px";
                    }
                },
                /**
                 * 获取筛选项——只针对人员筛选器
                 * tabObj：Object tab设置对象
                 */
                getFilter: function(tabObj) {
                    var loadingEl = "#" + this.$el.id + " .filter_option";
                    VanyAjax(tabObj.filterUrl, tabObj.params, "GET", loadingEl).done(function(data) {
                        for(var i = 0; i < data.length; i++) {
                            if(data[i].type === "input") {
                                data[i].model = "";
                            } else {
                                if(data[i].multiple) {
                                    data[i].model = [];
                                } else {
                                    data[i].model = "";
                                }
                            }
                            if(data[i].istree) {
                                if(data[i].key) {
                                    data[i].options = this.cleanTreeData(data[i].options, data[i].key, []);
                                } else {
                                    data[i].options = this.cleanTreeData(data[i].options, {
                                        id: "id",
                                        name: "name",
                                        children: "children"
                                    }, []);
                                }
                            } else {
                                if(data[i].key) {
                                    data[i].options = this.cleanSelectData(data[i].options, data[i].key);
                                }
                            }
                        };
                        tabObj.form.options = data;
                        this.getData(tabObj);
                        this.$nextTick(function() {
                            this.setHeight(tabObj);
                        });
                    }, false, this);
                },
                cleanTreeData: function(arr, keyObj, newArr) {
                    for(var i = 0; i < arr.length; i++) {
                        newArr.push({
                            text: arr[i][keyObj.name],
                            value: arr[i][keyObj.id]
                        });
                        if(arr[i][keyObj.children]) {
                            this.cleanTreeData(arr[i][keyObj.children], keyObj, newArr);
                        }
                    }
                    return newArr;
                },
                cleanSelectData: function(arr, keyObj) {
                    return arr.map(function(item) {
                        return {
                            text: item[keyObj.name],
                            value: item[keyObj.id]
                        }
                    });
                },
                getRowById: function(id, arr) {
                    for(var i = 0; i < arr.length; i++) {
                        if(id === arr[i].userId) {
                            return arr[i];
                        }
                    }
                    return false;
                },
                /**
                 * 获取tree数据
                 * tabObj：Object tab设置对象
                 */
                getData: function(tabObj) {
                    if(tabObj.pagination && tabObj.nodataFlag) {
                        return;
                    }
                    var loadingEl = "#" + this.$el.id + " .tree";
                    VanyAjax(tabObj.url, tabObj.params, "GET", loadingEl).done(function(data) {
                        // 分页逻辑判断
                        if(tabObj.pagination) {
                            if(data.total === 0) {
                                tabObj.nodataFlag = true;
                                return;
                            }
                            if(tabObj.params.pageIndex * tabObj.params.pageSize >= data.total) {
                                tabObj.nodataFlag = true;
                            }
                            tabObj.pages = data.pages;
                            tabObj.total = data.total;
                            tabObj.pageNum = data.pageNum;
                            tabObj.params.pageIndex++;
                            var temp_ = this._setAllNodesId(data.list, tabObj.id, tabObj.defaultProps);
                            for(var i = 0; i < temp_.length; i++) {
                                tabObj.data.push(temp_[i]);
                            }
                            if(!tabObj.firstLoad) {
                                // 监听scroll
                                var tablebody_ = this.$refs[tabObj.id][0].$el;
                                var self = this;
                                tablebody_ = tablebody_.getElementsByClassName("el-table__body-wrapper")[0];
                                tablebody_.onscroll = function(e) {
                                    self.paginationLoading(tabObj, e);
                                }
                                tabObj.firstLoad = true;
                            }
                            this.$nextTick(function() {
                                this.setHeight(tabObj);
                                var ref_ = this.$refs[tabObj.id][0];
                                if(tabObj.writeBackIds) {
                                    var writeBackIds = tabObj.writeBackIds.split(",");
                                    for(var i = 0; i < writeBackIds.length; i++) {
                                        var row = this.getRowById(writeBackIds[i], tabObj.data);
                                        if(row) {
                                            ref_.toggleRowSelection(row, true);
                                        }
                                    }
                                }
                            });
                        } else {
                            tabObj.data = this._setAllNodesId(data, tabObj.id, tabObj.defaultProps);
                            this.$nextTick(function() {
                                this.setHeight(tabObj);
                                var ref_ = this.$refs[tabObj.id][0];
                                if(tabObj.writeBackIds) {
                                    var writeBackIds = tabObj.writeBackIds.split(",");
                                    ref_.setCheckedKeys(writeBackIds);
                                }
                            });
                        }
                    }, false, this);
                },
                writeBack: function(tabId, checkedIds, singleSelet) {
                    var ref_ = this.$refs[tabId][0];
                    if(!singleSelet) {
                        ref_.setCheckedKeys(checkedIds.split(","));
                    } else {
                        ref_.setCurrentRow(checkedIds.split(","));
                    }
                },
                /**
                 * 勾选/取消勾选指定tab下树的所有节点
                 * checked：Boolean true表示勾选全部，false表示取消勾选全部
                 * tabName： String tab id
                 */
                checkAll: function(checked, tabName) {
                    var ref_ = this.$refs[tabName][0];
                    if(checked) {
                        var tabindex = this.getTabSettingByName(tabName),
                            allNodesId = this.getAllNodesId(this.tabs[tabindex].data, [], this.tabs[tabindex].defaultProps);
                        ref_.setCheckedKeys(allNodesId);
                    } else {
                        ref_.setCheckedKeys([]);
                    }
                },
                select: function(selection, row) {
                    var inFlag = [];
                    for(var i = 0; i < selection.length; i++) {
                        if(row.userId === selection[i].userId) {
                            inFlag.push(1);
                            break
                        }
                    }
                    if(inFlag.length === 0) {
                        var index_ = this.getTabSettingByName(row.treesrc_),
                            tab = this.tabs[index_],
                            ref_ = this.$refs[row.treesrc_][0];
                        for(var i = 0; i < tab.allNodesId.length; i++) {
                            if(row.userId === tab.allNodesId[i]) {
                                this.remove(row.userId, i, row.treesrc_, true);
                            }
                        }
                    }
                },
                /*用于人员筛选器*/
                selectionChange: function(selection, tabObj) {
                    if(selection.length) {
                        for(var i = 0; i < selection.length; i++) {
                            this.add(selection[i], tabObj);
                        }
                    } else {
                        for(var i = 0; i < tabObj.data.length; i++) {
                            for(var j = 0; j < tabObj.allNodesId.length; j++) {
                                if(tabObj.data[i].userId === tabObj.allNodesId[j]) {
                                    this.remove(tabObj.data[i].userId, j, tabObj.id, true);
                                    break;
                                }
                            }
                        }
                    }
                },
                /**
                 * 节点勾选状态发生改变的回调
                 * data：节点数据
                 * checked：节点勾选状态
                 * indeterminate：可忽略该参数
                 */
                handleCheckChange: function(data, checked, indeterminate) {
                    var index_ = this.getTabSettingByName(data.treesrc_),
                        tab = this.tabs[index_];
                    if(checked) {
                        this.add(data);
                    } else {
                        var index_ = this.getCheckedNodeIndex(data[tab.defaultProps.id], data.treesrc_);
                        /*索引可能是0
                         *这里应进行强类型判断
                         */
                        if(index_ !== false) {
                            this.remove(data[tab.defaultProps.id], index_, data.treesrc_, false);
                        }
                    }
                },
                /**
                 * 通过tab id获取该tab所在索引
                 * tabName：String 设置里面传入的tab id
                 * return i
                 * TODO：待优化
                 */
                getTabSettingByName: function(tabName) {
                    for(var i = 0; i < this.tabs.length; i++) {
                        if(tabName === this.tabs[i].id) {
                            return i;
                        }
                    }
                    return false;
                },
                /**
                 * 单击行的时候也能触发选中——内部方法
                 * 用户体验优化
                 */
                _handleCurrentChange: function(data, Node) {
                    var index_ = this.getTabSettingByName(data.treesrc_),
                        tab = this.tabs[index_];
                    if(tab.singleSelet) {
                        tab.allCheckeds = [];
                        tab.allNodesId = [];
                        this.add(data, tab);
                    } else {
                        Node.checked = !Node.checked;
                    }
                },
                /**
                 * 标记数据来源——内部方法
                 */
                _setAllNodesId: function(treeArray, tabName, defaultProps) {
                    for(var i = 0; i < treeArray.length; i++) {
                        treeArray[i]["treesrc_"] = tabName;
                        treeArray[i]["$checked"] = false;
                        if(treeArray[i][defaultProps.children]) {
                            this._setAllNodesId(treeArray[i][defaultProps.children], tabName, defaultProps);
                        }
                    }
                    return treeArray;
                },
                getAllNodesId: function(treeArray, resultArray, defaultProps) {
                    for(var i = 0; i < treeArray.length; i++) {
                        resultArray.push(treeArray[i][defaultProps.id]);
                        if(treeArray[i][defaultProps.children]) {
                            this.getAllNodesId(treeArray[i][defaultProps.children], resultArray, defaultProps);
                        }
                    }
                    return resultArray;
                },
                add: function(data, tabSetting) {
                    var index_ = this.getTabSettingByName(data.treesrc_),
                        tab = this.tabs[index_];
                    if(tab.allNodesId.indexOf(data[tab.defaultProps.id]) > -1) {
                        return;
                    }
                    if(tab.isPersonSeleted) {
                        data.$checked = true;
                        if(tab.isPersonSeleted) {
                            tab.allCheckeds.push({
                                type: data.type,
                                avater: data.photoUrl,
                                name: data[tab.defaultProps.label],
                                userId: data[tab.defaultProps.id]
                            });
                        } else {
                            tab.allCheckeds.push(data);
                        }
                    } else {
                        tab.allCheckeds.push({
                            type: data.type,
                            avater: data.photoUrl,
                            name: data[tab.defaultProps.label],
                            id: data[tab.defaultProps.id]
                        });
                    }
                    tab.allNodesId.push(data[tab.defaultProps.id]);
                },
                /**
                 * 获取指定tab下节点id在所有选中节点数组索引
                 * id：节点id
                 * treeSrc： String 设置里面传入的tab id
                 */
                getCheckedNodeIndex: function(id, treeSrc) {
                    var index_ = this.getTabSettingByName(treeSrc);
                    for(var i = 0; i < this.tabs[index_].allNodesId.length; i++) {
                        if(this.tabs[index_].allNodesId[i] === id) {
                            return i;
                        }
                    }
                    return false;
                },
                /**
                 * 取消勾选指定tab下的tree节点
                 * id：节点id
                 * treeSrc： String 设置里面传入的tab id
                 */
                unchecked: function(id, treeSrc) {
                    var index_ = this.getTabSettingByName(treeSrc),
                        tab = this.tabs[index_],
                        ref_ = this.$refs[tab.id][0];
                    if(ref_.setChecked) {
                        ref_.setChecked(id, false);
                    } else {
                        var row = this.getRowById(id, tab.data);
                        row.$checked = false;
                        ref_.toggleRowSelection(row, false);
                    }
                },
                remove: function(id, index, treeSrc, byTag) {
                    var index_ = this.getTabSettingByName(treeSrc);
                    this.tabs[index_].allCheckeds.splice(index, 1);
                    this.tabs[index_].allNodesId.splice(index, 1);
                    /*通过标签直接取消勾选
                     *则直接unchecked而不是通过tree提供的回掉处理
                     */
                    if(byTag) {
                        this.unchecked(id, treeSrc);
                    }
                },
                /**
                 * 确定按钮回调
                 * 如果回调函数返回false，则不关闭筛选器
                 */
                submit: function() {
                    if(setting.ok) {
                        if(isFunction(setting.ok)) {
                            if(setting.ok.call(this) !== false) {
                                this.hide();
                            }
                        } else {
                            throw new Error("setting.ok应该提供一个回调函数");
                        }
                    }
                },
                /**
                 * tab切换时显示隐藏对应的tab内容——内部方法
                 */
                _changeTab: function(tabInstance) {
                    var seleted_containers = this.$el.getElementsByClassName("seleted_container");
                    var index_ = parseInt(tabInstance.index);
                    for(var i = 0; i < this.tabs.length; i++) {
                        this.tabs[i].display.display = "none";
                        seleted_containers[i].style.display = "none";
                    }
                    this.tabs[index_].display.display = "block";
                    seleted_containers[index_].style.display = "block";
                },
                /**
                 * 显示筛选器
                 */
                show: function() {
                    this.visible = true;
                },
                /**
                 * 关闭筛选器
                 */
                hide: function() {
                    this.visible = false;
                },
                /**
                 * 销毁筛选器实例
                 * 注意：destroy后需要手工设置变量为null
                 * test = VanyFilter();
                 * test.destroy();
                 * test = null;
                 */
                destroy: function() {
                    this.hide();
                    this.$el.parentNode.removeChild(this.$el)
                },
                // TODO：搜索
                filterNode: function(value, data) {
                    if(!value) return true;
                    return data.label.indexOf(value) !== -1;
                },
                /**
                 * 重置筛选条件
                 * index: Number 重置哪个tab的筛选条件
                 */
                resetFilter: function(index) {
                    var options = this.tabs[index].form.options;
                    for(var i = 0; i < options.length; i++) {
                        if(options[i].type === "input") {
                            options[i].model = "";
                        } else {
                            if(options[i].multiple) {
                                options[i].model = [];
                            } else {
                                options[i].model = "";
                            }
                        }
                    }
                },
                resetPaginationParams: function(index) {
                    var tab = this.tabs[index];
                    if(tab.pagination) {
                        tab.data = [];
                        tab.nodataFlag = false;
                        tab.params.pageIndex = 1;
                        tab.writeBackIds = tab.allNodesId.join(",");
                    }
                    return this;
                },
                paginationLoading: function(tabObj, e) {
                    this._throttle(this._isScrollToBottom, e, this.getData, tabObj);
                },
                /**
                 * 判断一个可滚动元素是否滚动到了底部
                 */
                _isScrollToBottom: function(e, fn, context) {
                    // e.srcElement存在兼容性问题，并非标准特性
                    // https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
                    // 支持 IE6-8
                    var target_ = e.target || e.srcElement,
                        // 距离顶部高度
                        scrollTop = target_.scrollTop,
                        // 滚动区域高度
                        scrollHeight = target_.scrollHeight,
                        // 文档元素高度
                        clientHeight = target_.clientHeight;
                    // 文档坐标和视口坐标转换，判断元素滚动到了底部
                    if(scrollTop + clientHeight == scrollHeight) {
                        if(fn) {
                            fn.call(this, context);
                        }
                    }
                },
                /**
                 * 函数节流器
                 */
                _throttle: function(method, context) {
                    clearTimeout(method.tId);
                    var _arguments_ = arguments;
                    method.tId = setTimeout(function() {
                        var args = [];
                        for(var i = 1; i < _arguments_.length; i++) {
                            args.push(_arguments_[i]);
                        }
                        method.apply(this, args);
                    }, 100);
                },
                getFilterValue: function(index) {
                    this.resetPaginationParams(index);
                    var params = this.tabs[index].params;
                    var options = this.tabs[index].form.options;
                    for(var i = 0; i < options.length; i++) {
                        var key_ = options[i].formname;
                        if(options[i].type === "input") {
                            params[key_] = options[i].model;
                        } else {
                            if(options[i].multiple) {
                                params[key_] = options[i].model.join(",")
                            } else {
                                params[key_] = options[i].model;
                            }
                        }
                        if(params[key_].length === 0 || !params[key_]) {
                            delete params[key_];
                        }
                    }
                    this.getData(this.tabs[index]);
                },
                renderContent: function(h, node, data, store) {
                    var self = this;
                    return h("span", null, [h('span', null, node.label), h("span", {
                        style: {
                            float: "right"
                        },
                        domProps: {
                            innerHTML: "(" + node.key + "    " + data.genderStr + ")",
                        }
                    }, "")]);
                },
                getSelectedValue: function(index) {
                    try {
                        return this.tabs[index].allNodesId.join(",");
                    } catch(e) {
                        return "";
                    }
                },
                clear: function(index) {
                    var i,
                        length;
                    if(index) {
                        i = index;
                        length = index + 1;
                    } else {
                        i = 0;
                        length = this.tabs.length;
                    }
                    for(; i < length; i++) {
                        this.tabs[i].allCheckeds = [];
                        this.tabs[i].allNodesId = [];
                        try {
                            this.resetFilter(i);
                        } catch(e) {}
                        if(this.tabs[i].isPersonSeleted) {
                            this.$refs[this.tabs[i].id][0].clearSelection();
                        }
                    }
                }
            }
        });
        return vanyfilter;
    }

    /**
     * setting说明
     * mountEl：String 挂在元素id #id
     * title：String 筛选器标题
     * tabs：Array 筛选器tab设置
     * {
     * 	"name": tab名称
     * 	"id": tab id
     * 	"singleSelet"：Boolean 是否只支持单选默认多选
     * 	"url"：String 树数据请求地址
     * 	"writeBackIds"：String 需要回写的数据 逗号隔开的字符串
     * 	"defaultProps"：Object 树数据结构键名
     * 		{
     * 			"children": 'children',
    			"label": 'tagName',
    			"id": "tagCode"
     * 		}
     * }
     * ok：Function 确定按钮回调
     */
    window.VanyFilter = function(setting) {
        return new VanyFilter_(setting);
    }

    /************************************************VanyFilter结束************************************************/
})(window);